package com.blc.controller.oauth;

import com.alibaba.fastjson.JSON;
import com.blc.enums.WxEnums;
import com.blc.util.InteractionUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.HashMap;

/**
 * @Author tidudada
 * @Description  微信oauth2.0授权demo
 * @Date 上午9:16 2021/11/25
 **/
@Controller
@RequestMapping("erp")
public class MpOauthController {
    private final Logger logger = LoggerFactory.getLogger(MpOauthController.class);

    private final InteractionUtil interactionUtil = new InteractionUtil();

    @Value("${wx.blc.appid}")
    private String appid;
    
    @Value("${wx.blc.secret}")
    private String secret;


    // 拉起用户认证
    @RequestMapping("attestation/{flag}")
    public void attestation(HttpServletResponse response, @PathVariable String flag) throws IOException {
        // 用户授权后重定向地址
        String redirectUrl = "http://tidudada.5gzvip.91tunnel.com/erp/"+flag;
        URLEncoder.encode(redirectUrl,"utf-8");
        String url = WxEnums.MP_OAUTH.getUrl()
                .replace("APPID",appid)
                .replace("REDIRECT_URI",redirectUrl)
                .replace("SCOPE","snsapi_userinfo");
        logger.info("需要用户进行认证的");
        response.sendRedirect(url);
    }

    // 跟据响应code获取微信用户信息
    @RequestMapping(value = "order",method = RequestMethod.GET)
    public void order(HttpServletRequest request){
        String code = request.getParameter("code");
        String state = request.getParameter("state");
        String url = WxEnums.ACCREDIT_ACCESS_TOKEN.getUrl()
                .replace("APPID", appid)
                .replace("SECRET",state).replace("CODE", code);
        String message = interactionUtil.sendGet(url);
        // 用户的accessToken OpenId
        HashMap hashMap = JSON.parseObject(message, HashMap.class);
        String getUserInfo = WxEnums.GET_USERINFRO.getUrl().
                replace("ACCESS_TOKEN", hashMap.get("access_token") + "").replace("OPENID", hashMap.get("openid") + "");
        String userInfo = interactionUtil.sendGet(getUserInfo);
        logger.info(userInfo);
    }




}
